<template>
  <div class="forget-password">
    <div class="forget-password-title">{{ $t('login.forget-password') }}?</div>
    <div class="forget-password-form">
      <el-form
        :model="forgetPasswordForm"
        :rules="forgetPasswordRules"
        ref="forgetPasswordRef"
      >
        <el-form-item prop="email">
          <el-input
            v-model.trim="forgetPasswordForm.email"
            :placeholder="$t('login.enter-email')"
          />
        </el-form-item>
      </el-form>
    </div>
    <div class="send-button display-flex">
      <el-button
        class="flex-1"
        type="primary"
        @click="handleReset"
        :loading="resetLoading"
        >{{ $t('login.send-reset-link') }}</el-button
      >
    </div>
    <div class="display-flex">
      <el-button class="flex-1" @click="handleBack">{{
        $t('login.back')
      }}</el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { usePreferencesStore } from '@/stores'
import { delay } from '@/utils'
import { emailRegex } from '@/utils/modules/regexp'
import { type FormInstance, type FormRules } from 'element-plus'
import { reactive, ref, useTemplateRef, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { useRouter } from 'vue-router'

const router = useRouter()
const { t } = useI18n()
const preferencesStore = usePreferencesStore()

const forgetPasswordForm = ref({
  email: ''
})
const forgetPasswordRules = reactive<
  FormRules<typeof forgetPasswordForm.value>
>({
  email: [
    { required: true, message: t('login.enter-email'), trigger: 'blur' },
    {
      pattern: emailRegex,
      message: t('login.enter-valid-email'),
      trigger: 'blur'
    }
  ]
})
const forgetPasswordRef = useTemplateRef<FormInstance>('forgetPasswordRef')

const resetLoading = ref(false)
const handleReset = async () => {
  try {
    resetLoading.value = true
    await forgetPasswordRef.value?.validate()
    await delay(1000)
    ElMessage.success(t('login.reset-link-sent'))
  } catch (error) {
    return error
  } finally {
    resetLoading.value = false
  }
}

const handleBack = () => {
  router.replace('/login/enter')
}

watch(
  () => preferencesStore.general.lang.language,
  () => {
    if (forgetPasswordRules.email && Array.isArray(forgetPasswordRules.email)) {
      forgetPasswordRules.email[0].message = t('login.enter-email')
      forgetPasswordRules.email[1].message = t('login.enter-valid-email')
    }
  }
)

defineOptions({
  name: 'CoreForgetPassword'
})
</script>

<style scoped lang="scss">
.forget-password {
  margin: 24px 54px;

  .forget-password-title {
    margin-bottom: 22px;
    font-size: 36px;
    font-weight: 700;
  }

  .send-button {
    padding-top: 8px;
    margin-bottom: 16px;
  }
}
</style>
